import json
from huey.exceptions import TaskException

from src.tools.chain import gen_chain
from src.tools.excel_to_md import excel2md
from src.tools.extract_jsonstring import re_json_string, re_json_string_list
from src.gen_file.prompt import BPRMultiBagPrompt
from src.tools.dms_operator import dmsoperator
from src.tools.information_exchange import pub_gen
from src.tools.split_string import split_sub_string
from src.tools.mml_to_latex import mathml2latex
from src.tools.file_type import check_file_type1

class GenMultiBPRFile:

    def __init__(self):
        self.prompt = BPRMultiBagPrompt()

    # 解析批记录文件,提取要修改的段落和表格
    def parse_BPRjsonfile(self, json_data: dict):
        file_pubinfo = {
            "filePath": json_data["filePath"],
            "isHighlight": True,
            "editInfos": []
        }
        # 提取段落
        parainfo = []
        pre_key = ""
        for para in json_data["paragraphInfos"]:
            is_highlightcolor_para = False

            para_text = ""
            for textinfo in para["textInfos"]:
                if textinfo["subSuperscript"] == 2:
                    para_text += f'<sub>{textinfo["text"]}</sub>'
                else:
                    para_text += textinfo["text"]
                if textinfo["highlightColor"] != "0, 0, 0, 0":
                    is_highlightcolor_para = True

            mathinfos = []
            for mathinfo in para["officeMathInfos"]:
                if mathinfo["highlightColor"] != "0, 0, 0, 0":
                    is_highlightcolor_para = True
                math_dict = {
                    "text": mathml2latex(mathinfo["mathMlCode"])
                }
                mathinfos.append(math_dict)

            para_dict = {
                "index": para["index"],
                "sectionIndex": para["sectionIndex"],
                "bodyChildIndex": para["bodyChildIndex"],
                "pre_key": pre_key,
                "text": para_text,
                "latexMathInfos": mathinfos
            }
            if is_highlightcolor_para:
                parainfo.append(para_dict)
            pre_key = para["text"]
        # 提取表格
        tableinfo = []
        for table in json_data["tableInfos"]:
            is_table_highlightcolor = False
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "tableCellInfos": []
            }
            pre_key = ""
            _find_material_name = True
            for cell in table["tableCellInfos"]:
                # 标注高亮是修改部分,以cell为单位进行修改
                is_cell_highlightcolor = False
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "pre_key": pre_key,
                    "paragraphInfos": [],
                    "tableInfos": []
                }
                pre_key_para = ""
                for para in cell["paragraphInfos"]:
                    para_text = ""
                    for textinfo in para["textInfos"]:
                        if textinfo["subSuperscript"] == 2:
                            para_text += f'<sub>{textinfo["text"]}</sub>'
                        else:
                            para_text += textinfo["text"]
                        if textinfo["highlightColor"] != "0, 0, 0, 0":
                            is_cell_highlightcolor = True
                            is_table_highlightcolor = True

                    mathinfos = []
                    for mathinfo in para["officeMathInfos"]:
                        if mathinfo["highlightColor"] != "0, 0, 0, 0":
                            is_cell_highlightcolor = True
                            is_table_highlightcolor = True
                        math_dict = {
                            "text": mathml2latex(mathinfo["mathMlCode"])
                        }
                        mathinfos.append(math_dict)

                    para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "text": para_text,
                        "latexMathInfos": mathinfos
                    }
                    pre_key_para += para_text
                    cell_dict["paragraphInfos"].append(para_dict)
                is_cell_highlightcolor, is_table_highlightcolor = self.parse_sub_table(cell_dict["tableInfos"],
                                                                                       cell["tableInfos"],
                                                                                       is_cell_highlightcolor,
                                                                                       is_table_highlightcolor)
                pre_key = pre_key_para.replace(" ", "").rstrip()
                _find_material_name = self.find_material_name(int(cell["rowIndex"]) - 1, int(cell["columnIndex"]),
                                                              table["tableCellInfos"])
                if not _find_material_name and is_cell_highlightcolor:
                    table_dict["tableCellInfos"].append(cell_dict)
            if is_table_highlightcolor:
                tableinfo.append(table_dict)
        return file_pubinfo, parainfo, tableinfo

    # 解析内嵌表格
    def parse_sub_table(self, subtable_info: list, subtable_data: list, is_cell_highlightcolor: bool, is_table_highlightcolor: bool):
        for table in subtable_data:
            # 标注高亮是修改部分, 以table为单位进行修改
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "tableCellInfos": []
            }
            for cell in table["tableCellInfos"]:
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "paragraphInfos": []
                }
                for para in cell["paragraphInfos"]:
                    para_text = ""
                    for textinfo in para["textInfos"]:
                        if textinfo["subSuperscript"] == 2:
                            para_text += f'<sub>{textinfo["text"]}</sub>'
                        else:
                            para_text += textinfo["text"]
                        if textinfo["highlightColor"] != "0, 0, 0, 0":
                            is_cell_highlightcolor = True
                            is_table_highlightcolor = True
                    para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "text": para_text
                    }
                    cell_dict["paragraphInfos"].append(para_dict)
                table_dict["tableCellInfos"].append(cell_dict)
            subtable_info.append(table_dict)
        return is_cell_highlightcolor, is_table_highlightcolor

    # 找到流式输出内容
    def find_key_values(self, target_key,data):
        found_values = []
        if isinstance(data, dict):
            for key, value in data.items():
                if key == target_key and value:
                    found_values.append(value)
                found_values.extend(self.find_key_values(target_key, value))
        elif isinstance(data, list):
            for item in data:
                found_values.extend(self.find_key_values(target_key, item))
        return found_values

    # 利用生成链，生成要修改的内容
    def gen_BPRfile_para_table(self, content, extract_text, task_id, BPRfile):
        if content.get("pre_key") == "规格" or content.get("pre_key") == "产品规格":
            revise_BPRtext_query = self.prompt.gen_file_prompt(orig_BPRtext=json.dumps(content, ensure_ascii=False),
                                                          SOPtext=extract_text, special="4.如果json示例中的'pre_key'字段内容是产品规格，那么生成'text'字段内容只需要总规格，不要解释总规格的来源。\n")
        else:
            revise_BPRtext_query = self.prompt.gen_file_prompt(orig_BPRtext=json.dumps(content, ensure_ascii=False),
                                                          SOPtext=extract_text, special="")
        # print("-" * 100)
        # print(revise_BPRtext_query)
        # print("-" * 100)
        revise_BPRtext = gen_chain(revise_BPRtext_query)
        try:
            revise_BPRtext = re_json_string(revise_BPRtext)
            print(revise_BPRtext)
            revise_BPRtext_dict = json.loads(revise_BPRtext)
        except:
            print("json解析失败")
            revise_BPRtext_dict = content
        text_key = self.find_key_values("text", revise_BPRtext_dict)
        for msg in text_key:
            pub_gen(task_id, msg, BPRfile.get("docId"), BPRfile.get("taskDocId"))
        return revise_BPRtext_dict

    def gen_BPRfile_para_table_temp(self, content, extract_text, template_list, task_id, BPRfile):
        template_text = []
        for temp in template_list:
            template_text.append({"text": temp["text"], "tableCellInfos": temp["tableCellInfos"]})
        revise_BPRtext_query = self.prompt.gen_file_prompt_temp(orig_BPRtext=json.dumps(content, ensure_ascii=False),
                                                                SOPtext=extract_text, temp=str(template_text))
        print("-" * 100)
        print(revise_BPRtext_query)
        print("-" * 100)
        revise_BPRtext = gen_chain(revise_BPRtext_query)
        revise_BPRtext = re_json_string(revise_BPRtext)
        print(revise_BPRtext)
        revise_BPRtext_dict = json.loads(revise_BPRtext)
        text_key = self.find_key_values("text", revise_BPRtext_dict)
        for msg in text_key:
            pub_gen(task_id, msg, BPRfile.get("docId"), BPRfile.get("taskDocId"))
        return revise_BPRtext_dict

    # 修改表格结构
    def modify_table_structure(self, json_data: dict, material_info_dict: dict):
        tableinfo = []
        for table in json_data["tableInfos"]:
            is_table_highlightcolor = False
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "tableCellInfos": []
            }
            pre_key = ""
            pre_rowcount = None
            for cell in table["tableCellInfos"]:
                # 标注高亮是修改部分,以cell为单位进行修改
                is_cell_highlightcolor = False
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "pre_key": pre_key,
                    "pre_rowcount": pre_rowcount,
                    "paragraphInfos": []
                }
                pre_key_para = ""
                for para in cell["paragraphInfos"]:
                    para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "text": para["text"]
                    }
                    pre_key_para += para["text"]
                    cell_dict["paragraphInfos"].append(para_dict)
                    for para_text in para["textInfos"]:
                        if para_text["highlightColor"] != "0, 0, 0, 0" and ("称量计算" in pre_key or "称料量计算" in pre_key) :
                            is_cell_highlightcolor = True
                            is_table_highlightcolor = True
                            break
                pre_key = pre_key_para.rstrip("\n")
                pre_rowcount = cell["rowCount"]
                if is_cell_highlightcolor:
                    table_dict["tableCellInfos"].append(cell_dict)
            if is_table_highlightcolor:
                tableinfo.append(table_dict)
        edit_structure = []
        for table in tableinfo:
            for cell in table["tableCellInfos"]:
                if material_info_dict["count"] == cell["pre_rowcount"]:
                    continue
                elif material_info_dict["count"] > cell["pre_rowcount"]:
                    modify_dict = {
                        "index": table["index"],
                        "sectionIndex": table["sectionIndex"],
                        "bodyChildIndex": table["bodyChildIndex"],
                        "operationType": 0,
                        "documentObjectType": 2,
                        "cellOperationType": 2,
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "splitRowCount": material_info_dict["count"] - cell["pre_rowcount"] + 1,
                    }
                    edit_structure.append(modify_dict)
                else:
                    modify_dict = {
                        "index": table["index"],
                        "sectionIndex": table["sectionIndex"],
                        "bodyChildIndex": table["bodyChildIndex"],
                        "operationType": 0,
                        "documentObjectType": 2,
                        "cellOperationType": 1,
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "rows": cell["pre_rowcount"] - material_info_dict["count"] + 1,
                    }
                    edit_structure.append(modify_dict)


        if edit_structure:
            edit_structures = {
                "fileId": json_data["fileId"],
                "editContentInfos": edit_structure
            }
            print(edit_structures)
            edit_file = dmsoperator.post_edit_file(edit_structures)
            edit_file = json.loads(edit_file)
            print(edit_file)
            edit_file_jsondata = dmsoperator.get_jsonfile(edit_file["data"])

            return edit_file_jsondata
        return json_data

    # 查看单元格内容是否是原料名称
    def find_material_name(self, row_index, column_index, cellinfos):
        for cell in cellinfos:
            if cell["rowIndex"] == row_index and cell["columnIndex"] == column_index:
                cell_text = ""
                for para in cell["paragraphInfos"]:
                    cell_text += para["text"]
                if cell_text.strip() == "原料名称":
                    return True
        return False

    # 修改原料名称下的单元格内容
    def weigh_modif_file(self, prescription_info, prescription_name, json_data):
        materials_name_query = self.prompt.weigh_modif_file_prompt(prescription_info, prescription_name)
        materials_name_text = gen_chain(materials_name_query)
        materials_name = json.loads(re_json_string_list(materials_name_text))

        file_pubinfo = {
            "filePath": json_data["filePath"],
            "isHighlight": True,
            "editInfos": []
        }
        tableinfo = []
        for table in json_data["tableInfos"]:
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "tableCellInfos": []
            }
            _find_material_name = False
            for cell in table["tableCellInfos"]:
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "paragraphInfos": []
                }
                for para in cell["paragraphInfos"]:
                    para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "text": para["text"]
                    }
                    cell_dict["paragraphInfos"].append(para_dict)
                _find_material_name = self.find_material_name(int(cell["rowIndex"]) - 1, int(cell["columnIndex"]), table["tableCellInfos"])
                if _find_material_name:
                    table_dict["tableCellInfos"].append(cell_dict)
            tableinfo.append(table_dict)
        print(tableinfo)
        materials_name_index = 0
        for table in tableinfo:
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "operationType": 0,
                "tableInfo": {
                    "cellEditInfos": []
                }
            }
            for cell in table["tableCellInfos"]:
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "cellChildInfos": []
                }
                for para_index, para in enumerate(cell["paragraphInfos"]):
                    if para_index == 0:
                        textinfo_list = split_sub_string(materials_name[materials_name_index])
                        textinfos = []
                        for textinfo_index, textinfo in enumerate(textinfo_list):
                            textinfo_dict = {
                                "paragraphChildIndex": textinfo_index,
                                "paraChildType": 0,
                                "content": textinfo.get("content"),
                                "subSuperScript": textinfo.get("subSuperScript")
                            }
                            textinfos.append(textinfo_dict)
                        para_info = {
                            "index": para_index,
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 1,
                            "paragraphInfo": {
                                "paragraphChildInfos": textinfos,
                                "referenceParagraphType": 2
                            }
                        }
                        dele_para_info = {
                            "index": para_index,
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 2
                        }
                        cell_dict["cellChildInfos"].append(para_info)
                        cell_dict["cellChildInfos"].append(dele_para_info)
                        materials_name_index += 1
                        if materials_name_index == len(materials_name):
                            materials_name_index = 0
                    else:
                        para_info = {
                            "index": para_index,
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 2
                        }
                        cell_dict["cellChildInfos"].append(para_info)
                table_dict["tableInfo"]["cellEditInfos"].append(cell_dict)
            file_pubinfo["editInfos"].append(table_dict)
        print(json.dumps(file_pubinfo, indent=4, ensure_ascii=False))
        res_materials = dmsoperator.post_edit_file_v2(file_pubinfo)
        res_json = dmsoperator.get_jsonfile(res_materials["data"])
        return res_json


    #生成批记录文件
    def gen_BPRfile(self, content_files: list, BPRfile: dict, template_infos: list, task_id: str, change_info: dict, bproper_num: dict):
        # 获得要修改文件的json数据
        bprfile_jsondata = dmsoperator.get_jsonfile(BPRfile.get("realPath"))
        SOP_query, SOP_content_file_id, supplier_content_file_id, extract_text1, extract_text2, suppliertext, extract_supplier_text = "", "", "", "", "", "", ""
        # 找到要修改的批记录的环节
        for bpr_oper in ["称量", "配制", "灌封", "灭菌", "灯检", "包装"]:
            if bpr_oper in BPRfile.get("documentName"):
                SOP_query = bpr_oper
                break
        # 根据文件名和文件内容找到需要的内容来源文件
        for content_file in content_files:
            content_file_id_temp = content_file.get("realPath")
            if "工艺规程" in content_file.get("documentName") or "工艺规程" in check_file_type1(content_file_id_temp):
                SOP_content_file_id = content_file.get("realPath")

            if "供应商" in content_file.get("documentName") or "供应商目录" in check_file_type1(content_file_id_temp):
                supplier_content_file_id = content_file.get("realPath")
        # 没有工艺规程文件或供应商文件，则抛出异常
        if not SOP_content_file_id:
            errorinfo = {
                "FunctionType": change_info.get("functionType"),
                "TaskId": change_info.get("dmsTaskId"),
                "AiTaskId": task_id,
                "Reason": "未找到工艺规程文件"
            }
            dmsoperator.post_errortodms(errorinfo=errorinfo)
            raise TaskException("未找到工艺规程文件")
        if not supplier_content_file_id:
            errorinfo = {
                "FunctionType": change_info.get("functionType"),
                "TaskId": change_info.get("dmsTaskId"),
                "AiTaskId": task_id,
                "Reason": "未找到供应商文件"
            }
            dmsoperator.post_errortodms(errorinfo=errorinfo)
            raise TaskException("未找到供应商文件")
        # 称量配制环节需要单独提出信息
        if (SOP_query == "称量" or SOP_query == "配制") and SOP_content_file_id:
            print(SOP_content_file_id)
            SOPtext = dmsoperator.get_fileconversion(file_id=SOP_content_file_id, file_type_num=4).replace(
                'style="text-align: center;"', "").replace('style="text-align: left;"', "").replace(
                'style="text-align: right;"', "")
            # 提取处方名称
            prescription_query = self.prompt.prescription_prompt(SOPtext)
            print(prescription_query)
            prescription_text = gen_chain(prescription_query)
            prescription_list = json.loads(re_json_string_list(prescription_text))
            # 提取处方信息
            prescription_info_query, prescription_name = "", ""
            if "称量记录1" in BPRfile.get("documentName") or "配制记录1" in BPRfile.get("documentName"):
                prescription_info_query = self.prompt.prescription_info_prompt(SOPtext, prescription_list[0], SOP_query)
                prescription_name = prescription_list[0]
            elif "称量记录2" in BPRfile.get("documentName") or "配制记录2" in BPRfile.get("documentName"):
                prescription_info_query = self.prompt.prescription_info_prompt(SOPtext, prescription_list[1], SOP_query)
                prescription_name = prescription_list[1]
            elif "称量记录3" in BPRfile.get("documentName") or "配制记录3" in BPRfile.get("documentName"):
                prescription_info_query = self.prompt.prescription_info_prompt(SOPtext, prescription_list[2], SOP_query)
                prescription_name = prescription_list[2]
            # prescription_info_query = self.prompt.prescription_info_prompt(SOPtext, prescription_list[bproper_num.get(SOP_query)], SOP_query)
            prescription_info = gen_chain(prescription_info_query)
            # bproper_num[SOP_query] += 1
            pub_gen(task_id, prescription_info, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(prescription_info)
            # 称量环节需要填写原料名称
            if SOP_query == "称量":
                # bprfile_jsondata = self.weigh_modif_file(prescription_info, prescription_list[bproper_num.get(SOP_query) - 1], bprfile_jsondata)
                bprfile_jsondata = self.weigh_modif_file(prescription_info, prescription_name, bprfile_jsondata)
            extract_text2 = prescription_info
            # 提取除工艺操作外的内容
            extract_query1 = self.prompt.extract_SOPinfo_prompt1(SOPtext)
            extract_text1 = gen_chain(extract_query1)
            pub_gen(task_id, extract_text1, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_text1)
        # 除称量配制环节，其余环节提取信息
        if SOP_query != "称量" and SOP_query != "配制" and SOP_content_file_id:
            SOPtext = dmsoperator.get_fileconversion(file_id=SOP_content_file_id, file_type_num=4).replace('style="text-align: center;"', "").replace('style="text-align: left;"', "").replace('style="text-align: right;"', "")
            # 提取除工艺操作外的内容
            extract_query1 = self.prompt.extract_SOPinfo_prompt1(SOPtext)
            extract_text1 = gen_chain(extract_query1)
            pub_gen(task_id, extract_text1, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_text1)
            # 提取特定工艺操作的内容,比如灭菌
            extract_query2 = self.prompt.extract_SOPinfo_prompt2(query=SOP_query, article=SOPtext)
            extract_text2 = gen_chain(extract_query2)
            pub_gen(task_id, extract_text2, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_text2)
        # 提取供应商目录信息
        if supplier_content_file_id:
            if supplier_content_file_id.endswith(('.xls', '.xlsx')):
                suppliertext = excel2md(supplier_content_file_id)
            else:
                suppliertext = dmsoperator.get_fileconversion(file_id=supplier_content_file_id, file_type_num=4).replace('style="text-align: center;"', "").replace('style="text-align: left;"', "").replace('style="text-align: right;"', "")
            extract_supplier_query = self.prompt.extract_supplierinfo_prompt1(query=extract_text1, article=suppliertext)
            extract_supplier_text = gen_chain(extract_supplier_query)
            pub_gen(task_id, extract_supplier_text, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_supplier_text)

        # 原料信息
        # material_info_query = self.prompt.extract_material_prompt(extract_text1)
        # material_info = gen_chain(material_info_query)
        # material_info = re_json_string(material_info)
        # print(material_info)
        # material_info_dict = json.loads(material_info)
        # bprfile_jsondata = self.modify_table_structure(bprfile_jsondata, material_info_dict)
        extract_text = extract_text1 + "\n" + extract_text2 + "\n" + extract_supplier_text
        print(extract_text)
        file_pubinfo, parainfo, tableinfo = self.parse_BPRjsonfile(bprfile_jsondata)
        gen_filename = "生成的文件"
        table_i = -1
        # 修改段落
        for i, para in enumerate(parainfo):
            # if not template_infos[i]["source"]:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table(para, extract_text, task_id, BPRfile)
            # else:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table_temp(para, extract_text, template_infos[i]["source"], task_id, BPRfile)
            revise_BPRtext_dict = self.gen_BPRfile_para_table(para, extract_text, task_id, BPRfile)

            edit_para_dict = {
                "index": revise_BPRtext_dict["index"],
                "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                "operationType": 1,
                "paragraphInfo": {
                    "paragraphChildInfos": [],
                    "referenceParagraphType": 2
                }
            }
            # 插入纯文本
            textinfo_list = split_sub_string(revise_BPRtext_dict["text"])
            textinfos = []
            for textinfo_index, textinfo in enumerate(textinfo_list):
                textinfo_dict = {
                    "paragraphChildIndex": textinfo_index,
                    "paraChildType": 0,
                    "content": textinfo.get("content"),
                    "subSuperScript": textinfo.get("subSuperScript")
                }
                textinfos.append(textinfo_dict)
            if textinfos:
                edit_para_dict["paragraphInfo"]["paragraphChildInfos"] += textinfos
            # 插入数学式
            if revise_BPRtext_dict["latexMathInfos"]:
                latex_index = len(textinfos)
                mathinfos = []
                for latex_math_info in revise_BPRtext_dict["latexMathInfos"]:
                    mathinfo_dict = {
                        "paragraphChildIndex": latex_index,
                        "paraChildType": 2,
                        "content": latex_math_info["text"]
                    }
                    latex_index += 1
                    mathinfos.append(mathinfo_dict)
                edit_para_dict["paragraphInfo"]["paragraphChildInfos"] += mathinfos
            file_pubinfo["editInfos"].append(edit_para_dict)
            dele_edit_dict = {
                "index": revise_BPRtext_dict["index"],
                "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                "operationType": 2
            }
            file_pubinfo["editInfos"].append(dele_edit_dict)
            if i == 0:
                gen_filename = revise_BPRtext_dict["text"]
            table_i = i

        # 修改表格
        for table in tableinfo:
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "operationType": 0,
                "tableInfo": {
                    "cellEditInfos": []
                }
            }
            for cell in table["tableCellInfos"]:
                table_i += 1
                # if not template_infos[table_i]["source"]:
                #     revise_BPRtext_dict = self.gen_BPRfile_para_table(cell, extract_text, task_id, BPRfile)
                # else:
                #     revise_BPRtext_dict = self.gen_BPRfile_para_table_temp(cell, extract_text, template_infos[table_i]["source"], task_id, BPRfile)
                revise_BPRtext_dict = self.gen_BPRfile_para_table(cell, extract_text, task_id, BPRfile)
                cell_dict = {
                    "rowIndex": revise_BPRtext_dict["rowIndex"],
                    "columnIndex": revise_BPRtext_dict["columnIndex"],
                    "cellChildInfos": []
                }
                for para in revise_BPRtext_dict["paragraphInfos"]:

                    if para["text"] and table_i == 0 and para["index"] == 0:
                        gen_filename = para["text"]

                    edit_para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "operationType": 1,
                        "paragraphInfo": {
                            "paragraphChildInfos": [],
                            "referenceParagraphType": 2
                        }
                    }
                    # 插入纯文本
                    textinfo_list = split_sub_string(para["text"])
                    textinfos = []
                    for textinfo_index, textinfo in enumerate(textinfo_list):
                        textinfo_dict = {
                            "paragraphChildIndex": textinfo_index,
                            "paraChildType": 0,
                            "content": textinfo.get("content"),
                            "subSuperScript": textinfo.get("subSuperScript")
                        }
                        textinfos.append(textinfo_dict)
                    if textinfos:
                        edit_para_dict["paragraphInfo"]["paragraphChildInfos"] += textinfos
                    # 插入数学式
                    if para["latexMathInfos"]:
                        latex_index = len(textinfos)
                        mathinfos = []
                        for latex_math_info in para["latexMathInfos"]:
                            mathinfo_dict = {
                                "paragraphChildIndex": latex_index,
                                "paraChildType": 2,
                                "content": latex_math_info["text"]
                            }
                            latex_index += 1
                            mathinfos.append(mathinfo_dict)
                        edit_para_dict["paragraphInfo"]["paragraphChildInfos"] += mathinfos
                    cell_dict["cellChildInfos"].append(edit_para_dict)
                    # 删除段落，要判断是否在原文档段落index范围内
                    if para["index"] < len(cell["paragraphInfos"]):
                        dele_para_dict = {
                            "index": para["index"],
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 2
                        }
                        cell_dict["cellChildInfos"].append(dele_para_dict)
                # 如果生成的内容的index少于原内容的index，则删除剩余的段落
                if len(revise_BPRtext_dict["paragraphInfos"]) < len(cell["paragraphInfos"]):
                    for cell_para in cell["paragraphInfos"]:
                        if cell_para["index"] >= len(revise_BPRtext_dict["paragraphInfos"]):
                            dele_para_dict = {
                                "index": cell_para["index"],
                                "sectionIndex": cell_para["sectionIndex"],
                                "bodyChildIndex": cell_para["bodyChildIndex"],
                                "operationType": 2
                            }
                            cell_dict["cellChildInfos"].append(dele_para_dict)

                self.gen_sub_table(cell_dict["cellChildInfos"], revise_BPRtext_dict["tableInfos"], cell["tableInfos"])

                table_dict["tableInfo"]["cellEditInfos"].append(cell_dict)
            file_pubinfo["editInfos"].append(table_dict)

        print("-"*200)
        file_pubinfo_json = json.dumps(file_pubinfo, indent=4, ensure_ascii=False)
        print(file_pubinfo_json)
        # # 保存修改的json文件
        # edit_SOPjsonfile_path = f"修改.json"
        # with open(edit_SOPjsonfile_path, "w", encoding="utf-8") as f:
        #     f.write(file_pubinfo_json)
        print("-"*200)
        # 修改文件
        gen_res = dmsoperator.post_edit_file_v2(file_pubinfo)
        return gen_res["data"], gen_filename+".docx", bproper_num

    #生成内嵌列表
    def gen_sub_table(self, subtable_info: list, subtable_data: list, org_table_data: list):
        for table_index, table in enumerate(subtable_data):
            # 以table为单位进行修改
            # 判断生成的表格行数和原表格行数是否一致
            # 一致，直接修改，不一致，删除表格，重新生成
            if len(table["tableCellInfos"]) == len(org_table_data[table_index]["tableCellInfos"]):
                table_dict = {
                    "index": table["index"],
                    "sectionIndex": table["sectionIndex"],
                    "bodyChildIndex": table["bodyChildIndex"],
                    "operationType": 0,
                    "tableInfo": {
                        "cellEditInfos": []
                    }
                }
                for cell in table["tableCellInfos"]:
                    cell_dict = {
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "cellChildInfos": []
                    }
                    for para in cell["paragraphInfos"]:
                        textinfo_list = split_sub_string(para["text"])
                        textinfos = []
                        for textinfo_index, textinfo in enumerate(textinfo_list):
                            textinfo_dict = {
                                "paragraphChildIndex": textinfo_index,
                                "paraChildType": 0,
                                "content": textinfo.get("content"),
                                "subSuperScript": textinfo.get("subSuperScript")
                            }
                            textinfos.append(textinfo_dict)
                        para_dict = {
                            "index": para["index"],
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 1,
                            "paragraphInfo": {
                                "paragraphChildInfos": textinfos,
                                "referenceParagraphType": 2
                            }
                        }
                        dele_para_dict = {
                            "index": para["index"],
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 2
                        }
                        cell_dict["cellChildInfos"].append(para_dict)
                        cell_dict["cellChildInfos"].append(dele_para_dict)
                    table_dict["tableInfo"]["cellEditInfos"].append(cell_dict)
                subtable_info.append(table_dict)

            else:
                # 先插入表格
                max_row = -1
                max_column = -1
                for cell in table["tableCellInfos"]:
                    max_row = max(cell["rowIndex"], max_row)
                    max_column = max(cell["columnIndex"], max_column)
                row_num = max_row + 1
                column_num = max_column + 1
                table_dict = {
                    "index": table["index"],
                    "sectionIndex": table["sectionIndex"],
                    "bodyChildIndex": table["bodyChildIndex"],
                    "operationType": 1,
                    "tableInfo": {
                        "tableInsertInfo": {
                            "rowCount": row_num,
                            "columnCount": column_num,
                            "cellInsertInfos": []
                        }
                    }
                }
                for cell in table["tableCellInfos"]:
                    cell_dict = {
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "cellInsertContentInfos": []
                    }
                    for para in cell["paragraphInfos"]:
                        textinfo_list = split_sub_string(para["text"])
                        textinfos = []
                        for textinfo_index, textinfo in enumerate(textinfo_list):
                            textinfo_dict = {
                                "paragraphChildIndex": textinfo_index,
                                "paraChildType": 0,
                                "content": textinfo.get("content"),
                                "subSuperScript": textinfo.get("subSuperScript")
                            }
                            textinfos.append(textinfo_dict)
                        para_dict = {
                            "index": para["index"],
                            "paragraphInfo": {
                                "paragraphChildInfos": textinfos,
                            }
                        }
                        cell_dict["cellInsertContentInfos"].append(para_dict)
                    table_dict["tableInfo"]["tableInsertInfo"]["cellInsertInfos"].append(cell_dict)
                subtable_info.append(table_dict)
                # 再删除表格
                dele_table = {
                    "index": table["index"],
                    "sectionIndex": table["sectionIndex"],
                    "bodyChildIndex": table["bodyChildIndex"],
                    "operationType": 2,
                }
                subtable_info.append(dele_table)

